package com.cdck.safe.dete.common.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.cdck.safe.dete.model.dto.FileInfo;

import lombok.SneakyThrows;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author xiaozhu
 * @date 2024/2/27 9:32
 */
public class FileUtil {

    /**
     * 图片上传
     * @param file 图片文件
     * @return 结果信息
     */
    @SneakyThrows
    public static FileInfo uploadImageFile(MultipartFile file, String resourceFilePath, String pfx) {
        String fileName = IdUtil.fastSimpleUUID() + StrUtil.DOT + cn.hutool.core.io.FileUtil.extName(file.getOriginalFilename());
        String filePath = resourceFilePath + "image/";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File newFile = new File(fileDir, fileName);
        byte[] fileBytes = file.getBytes();

        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //暂时拼接请求路径
//        String absolutePath = newFile.getAbsolutePath();
//        long fileSize = FileUtils.sizeOf(newFile);
        String md5 = MD5.create().digestHex(fileBytes);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(fileName);
        fileInfo.setUrl(spliceImageUrl(pfx, fileName));
        return fileInfo;
    }

    /**
     * 拼接图片请求路径
     * @param pfx 请求前缀
     * @param fileName 图片名称加后缀
     * @return 图片请求静态资源路径
     */
    public static String spliceImageUrl(String pfx, String fileName){
        if(StringUtils.hasText(fileName)){
            return pfx + fileName;
        }else{
            return "";
        }
    }

}
